package kuang.producer_consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author hang
 * A执行完，调用B
 * B执行完，调用C
 * C执行完，调用A
 */
public class Test3 {

    public static void main(String[] args) {
        Data3 data = new Data3();

        new Thread(() -> {
            for(int i = 0; i < 10; i++){
                data.printA();
            }
        }, "A").start();

        new Thread(() -> {
            for(int i = 0; i < 10; i++){
                data.printB();
            }
        }, "B").start();

        new Thread(() -> {
            for(int i = 0; i < 10; i++){
                data.printC();
            }
        }, "C").start();
    }
}


class Data3{


    private Lock lock = new ReentrantLock();

    //可以通过监视器来判断执行那个对象
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    private int number = 1; //1A 2B 3C

    public void printA(){
        lock.lock();
        try {
            //业务--判断--执行--通知
            while(number != 1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "AAAA");
            number = 2;
            //精准控制哪个监视器可以唤醒，对应的那个监视器的代码就继续进行。
            //如果这个案例中使用一个监视器也是可以的，因为有number变量进行控制
            //我们使用三个控制器可以精准的使对应代码执行，而不会使其他监视器后的代码执行
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {
            while(number != 2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "BBBB");
            number = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {
            while(number != 3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "CCCC");
            number = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
